<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入音频标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择分类" clearable class="!w-240px">
          <el-option label="最近" value="recent" />
          <el-option label="英文" value="english" />
          <el-option label="中文" value="chinese" />
          <el-option label="收藏" value="favorite" />
        </el-select>
      </el-form-item>
      <el-form-item label="语言" prop="language">
        <el-select v-model="queryParams.language" placeholder="请选择语言" clearable class="!w-240px">
          <el-option label="英文" value="en" />
          <el-option label="中文" value="zh" />
          <el-option label="双语" value="bilingual" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-select v-model="queryParams.enabled" placeholder="请选择状态" clearable class="!w-240px">
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" width="80" />
      <el-table-column label="封面" align="center" prop="cover" width="100">
        <template #default="scope">
          <img v-if="scope.row.cover" :src="scope.row.cover" alt="封面" class="h-16 w-16 object-cover rounded" />
          <span v-else class="text-gray-400">无封面</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" min-width="150" />
      <el-table-column label="副标题" align="center" prop="subtitle" min-width="120" />
      <el-table-column label="分类" align="center" prop="category" width="100">
        <template #default="scope">
          <el-tag :type="getCategoryTagType(scope.row.category)">
            {{ getCategoryText(scope.row.category) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="语言" align="center" prop="language" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.language" :type="scope.row.language === 'en' ? 'primary' : 'success'">
            {{ getLanguageText(scope.row.language) }}
          </el-tag>
          <span v-else class="text-gray-400">-</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定内容" align="center" min-width="140">
        <template #default="scope">
          <div v-if="scope.row.bookTitle || scope.row.bookSetTitle">
            <div v-if="scope.row.bookTitle" class="text-sm font-medium text-blue-600">
              <Icon icon="ep:document" class="mr-1" />
              {{ scope.row.bookTitle }}
            </div>
            <div v-if="scope.row.bookSetTitle" class="text-xs text-gray-500 mt-1">
              来自: {{ scope.row.bookSetTitle }}
            </div>
            <div v-if="!scope.row.bookTitle && scope.row.bookSetTitle" class="text-sm text-orange-600">
              <Icon icon="ep:folder" class="mr-1" />
              {{ scope.row.bookSetTitle }}
            </div>
          </div>
          <span v-else class="text-gray-400">未绑定</span>
        </template>
      </el-table-column>
      <el-table-column label="时长" align="center" prop="duration" width="80">
        <template #default="scope">
          <span v-if="scope.row.duration">{{ formatDuration(scope.row.duration) }}</span>
          <span v-else class="text-gray-400">-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="enabled" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.enabled ? 'success' : 'danger'">
            {{ scope.row.enabled ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="240">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            :type="scope.row.enabled ? 'warning' : 'success'"
            @click="handleToggleStatus(scope.row)"
          >
            {{ scope.row.enabled ? '禁用' : '启用' }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            :loading="deleteLoading[scope.row.id]"
            :disabled="deleteLoading[scope.row.id]"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AudioForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import * as AudioApi from '@/api/reading/audio'
import AudioForm from './AudioForm.vue'

/** 音频资源管理 */
defineOptions({ name: 'AudioResourceManagement' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const deleteLoading = ref<Record<number, boolean>>({}) // 删除按钮的加载状态
const exportLoading = ref(false) // 导出按钮的加载状态
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  title: undefined,
  category: undefined,
  language: undefined,
  enabled: undefined
})
const queryFormRef = ref() // 搜索的表单
const formRef = ref() // 表单 Ref

// 注意：文件URL由后端直接返回完整地址，前端不再进行URL转换

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AudioApi.getAudioResourcePage(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error: any) {
    console.error('获取音频列表失败:', error)
    if (error?.response?.data?.msg) {
      message.error('获取列表失败: ' + error.response.data.msg)
    } else {
      message.error('获取列表失败，请稍后重试')
    }
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    exportLoading.value = true
    // 这里可以调用导出API
    message.success('导出功能开发中...')
  } catch (error: any) {
    console.error('导出失败:', error)
    message.error('导出失败，请稍后重试')
  } finally {
    exportLoading.value = false
  }
}

/** 状态切换操作 */
const handleToggleStatus = async (row: any) => {
  try {
    const newStatus = !row.enabled
    const action = newStatus ? '启用' : '禁用'

    await message.confirm(`确定要${action}该音频吗？`)

    await AudioApi.updateAudioResource({
      id: row.id,
      title: row.title,
      subtitle: row.subtitle,
      audioUrl: row.audioUrl,
      cover: row.cover,
      duration: row.duration,
      category: row.category,
      language: row.language,
      bookId: row.bookId,
      bookSetId: row.bookSetId,
      sortOrder: row.sortOrder,
      enabled: newStatus
    })

    message.success(`${action}成功`)
    await getList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('状态切换失败:', error)
      if (error?.response?.data?.msg) {
        message.error('操作失败: ' + error.response.data.msg)
      } else {
        message.error('操作失败，请稍后重试')
      }
    }
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()

    // 设置删除按钮加载状态
    deleteLoading.value[id] = true

    // 发起删除
    await AudioApi.deleteAudioResource(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除音频失败:', error)
      if (error?.response?.data?.msg) {
        message.error('删除失败: ' + error.response.data.msg)
      } else {
        message.error('删除失败，请稍后重试')
      }
    }
  } finally {
    // 清除删除按钮加载状态
    delete deleteLoading.value[id]
  }
}

/** 获取分类标签类型 */
const getCategoryTagType = (category: string) => {
  const typeMap = {
    'recent': 'info',
    'english': 'primary',
    'chinese': 'success',
    'favorite': 'warning'
  }
  return typeMap[category] || 'info'
}

/** 获取分类文本 */
const getCategoryText = (category: string) => {
  const textMap = {
    'recent': '最近',
    'english': '英文',
    'chinese': '中文',
    'favorite': '收藏'
  }
  return textMap[category] || category
}

/** 获取语言文本 */
const getLanguageText = (language: string) => {
  const textMap = {
    'en': '英文',
    'zh': '中文',
    'bilingual': '双语'
  }
  return textMap[language] || language
}

/** 格式化时长 */
const formatDuration = (duration: number) => {
  const minutes = Math.floor(duration / 60)
  const seconds = duration % 60
  return `${minutes}:${seconds.toString().padStart(2, '0')}`
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
